package com.netty.prictice.first;


import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;

import java.nio.ByteBuffer;

/**
 * @author shengtao
 * @Description:
 * @date 2018/09/04 16:41
 */
public class DiscardServerHandler extends ChannelHandlerAdapter {

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

   /* @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 丢弃客户端发来的数据.
        ((ByteBuf)msg).release();
        System.out.println("发送成功：");
//        try {
//
//        }finally {
//            //切记不要忘记释放缓冲区
//            ReferenceCountUtil.release(msg);
//        }
    }*/

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf message = (ByteBuf) msg;
       /* try {

            while (message.isReadable()){

                System.out.println(message.toString(io.netty.util.CharsetUtil.US_ASCII)+"----"+message.readByte());
                System.out.flush();
            }


        }finally {
            ReferenceCountUtil.release(msg);
        }*/
       try {
           ctx.write(msg);
           ctx.flush();
       }finally {
           ReferenceCountUtil.release(msg);
       }

    }
}
